import * as Cesium from "cesium";

export default class GridCell {

  // 存储键- 索引的映射 - 用于快速查找立方体 (O(1)查找优化)
  GridCellMap = new Map()

  // 存储网格单元实体数据
  GridCellLayer = []

  // 添加当前层索引指针
  currentLayerIndex = 0

  // 添加当前无人机位置跟踪
  currentUAVLayer = null

  constructor(viewer, position, size = 15.0) {
    this.viewer = viewer;
    this.position = position;
    // 立方体大小
    this.halfSize = size / 2;

    // 将[经度,纬度,高度]数组转换为Cartesian3对象
    const cartesian = Cesium.Cartesian3.fromDegrees(
      position[0],
      position[1],
      position[2]
    );

    // 创建一个局部坐标系的变换矩阵，防止因地球曲率导致的变形
    const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
    const orientation = Cesium.Transforms.headingPitchRollQuaternion(
      cartesian,
      hpr
    );
    this.modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
      cartesian, // 平移
      orientation, // 旋转
      new Cesium.Cartesian3(1, 1, 1) // 缩放
    );

    // 重新计算逆矩阵
    this.inverseMatrix = Cesium.Matrix4.inverse(
      this.modelMatrix,
      new Cesium.Matrix4()
    );

    this.allColor = {
      // 异常
      Red: new Cesium.Color(1.0, 0.0, 0.0, 0.3),
      // 警告
      Yellow: new Cesium.Color(1.0, 1.0, 0.0, 0.3),
      // 计划
      Green: new Cesium.Color(0.5, 1.0, 0.5, 0.3),
      // 当前网格 - 自定义绿色高亮 RGB(50, 205, 50)
      DarkGreen: new Cesium.Color(0.0, 1.0, 0.0, 0.3),
      // 正常
      White: new Cesium.Color(1.0, 1.0, 1.0, 0.3),
    };

    // 启用场景抗锯齿
    this.viewer.scene.postProcessStages.fxaa.enabled = true;

    // 初始化几何数据
    this.initGeometryData();

    // 存储创建的primitives
    this.primitiveRed = null;
    this.primitiveYellow = null;
    this.primitiveGreen = null;
    this.primitiveDarkGreen = null;
    this.primitiveWhite = null;
    this.edgePrimitive = null;
  }

  initGeometryData () {
    // 顶点坐标
    this.positions = new Float64Array([
      -this.halfSize, -this.halfSize, -this.halfSize, // 0
      this.halfSize, -this.halfSize, -this.halfSize,  // 1
      this.halfSize, this.halfSize, -this.halfSize,   // 2
      -this.halfSize, this.halfSize, -this.halfSize,  // 3
      -this.halfSize, -this.halfSize, this.halfSize,  // 4
      this.halfSize, -this.halfSize, this.halfSize,   // 5
      this.halfSize, this.halfSize, this.halfSize,    // 6
      -this.halfSize, this.halfSize, this.halfSize,   // 7
    ]);

    // 索引
    this.indices = new Uint16Array([
      0, 1, 2, 0, 2, 3, // 底面
      4, 5, 6, 4, 6, 7, // 顶面
      0, 1, 5, 0, 5, 4, // 前面
      1, 2, 6, 1, 6, 5, // 右面
      2, 3, 7, 2, 7, 6, // 后面
      3, 0, 4, 3, 4, 7, // 左面
    ]);

    // 基础层数据
    const baseLayer = {
      positions: new Float64Array(this.positions),
      indices: new Uint16Array(this.indices),
      color: "White",
      keyIndex: [0, 0, 0],
      show: true
    };

    // 初始化数据结构
    this.GridCellLayer = [baseLayer];

    // 使用keyIndex创建Map键，实现O(1)查找
    const mapKey = this.getMapKey([0, 0, 0]);
    this.GridCellMap.set(mapKey, 0); // 存储索引而不是对象本身
  }

  // 生成Map键的辅助方法
  getMapKey (keyIndex) {
    return `${keyIndex[0]}_${keyIndex[1]}_${keyIndex[2]}`;
  }

  // 向指定方向添加一个立方体 - Map优化版本
  extend (direction, offset = 1, color) {
    console.log("extend->color->", color);

    // 获取当前基准层的立方体数据
    const currentLayer = this.GridCellLayer[this.currentLayerIndex];
    const lastPositions = currentLayer.positions;
    const lastKeyIndex = currentLayer.keyIndex || [0, 0, 0];

    // 计算偏移距离
    const distance = this.halfSize * 2 * offset;

    // 根据方向更新keyIndex
    let newKeyIndex = [...lastKeyIndex];
    switch (direction) {
      case "1_0_0":
        newKeyIndex[0] = lastKeyIndex[0] + 1;
        break;
      case "-1_0_0":
        newKeyIndex[0] = lastKeyIndex[0] - 1;
        break;
      case "0_1_0":
        newKeyIndex[1] = lastKeyIndex[1] + 1;
        break;
      case "0_-1_0":
        newKeyIndex[1] = lastKeyIndex[1] - 1;
        break;
      case "0_0_1":
        newKeyIndex[2] = lastKeyIndex[2] + 1;
        break;
      case "0_0_-1":
        newKeyIndex[2] = lastKeyIndex[2] - 1;
        break;
    }

    // 使用Map进行O(1)查找
    const mapKey = this.getMapKey(newKeyIndex);
    const existingLayerIndex = this.GridCellMap.get(mapKey);

    // 如果存在相同keyIndex的层，只更新颜色并更新当前指针
    if (existingLayerIndex !== undefined) {
      console.log("已存在相同keyIndex的立方体，更新颜色");
      this.GridCellLayer[existingLayerIndex].color = color;
      this.GridCellLayer[existingLayerIndex].show = true;
      this.currentLayerIndex = existingLayerIndex;
      this.rebuildGeometry();
      return this;
    }

    // 创建新的顶点数组
    const newPositions = new Float64Array(lastPositions.length);

    // 复制立方体的顶点并根据方向添加偏移
    for (let i = 0; i < lastPositions.length; i += 3) {
      newPositions[i] = lastPositions[i];
      newPositions[i + 1] = lastPositions[i + 1];
      newPositions[i + 2] = lastPositions[i + 2];

      switch (direction.toLowerCase()) {
        case "1_0_0":
          newPositions[i] = lastPositions[i] - distance;
          break;
        case "-1_0_0":
          newPositions[i] = lastPositions[i] + distance;
          break;
        case "0_1_0":
          newPositions[i + 1] = lastPositions[i + 1] - distance;
          break;
        case "0_-1_0":
          newPositions[i + 1] = lastPositions[i + 1] + distance;
          break;
        case "0_0_1":
          newPositions[i + 2] = lastPositions[i + 2] + distance;
          break;
        case "0_0_-1":
          newPositions[i + 2] = lastPositions[i + 2] - distance;
          break;
        default:
          console.warn("无效的方向:", direction);
          return this;
      }
    }

    // 计算新立方体的中心点坐标
    const center = [0, 0, 0];
    for (let i = 0; i < newPositions.length; i += 3) {
      center[0] += newPositions[i] / 8;
      center[1] += newPositions[i + 1] / 8;
      center[2] += newPositions[i + 2] / 8;
    }

    const localCenter = new Cesium.Cartesian3(center[0], center[1], center[2]);
    const worldCenter = Cesium.Matrix4.multiplyByPoint(
      this.modelMatrix,
      localCenter,
      new Cesium.Cartesian3()
    );
    const cartographic = Cesium.Cartographic.fromCartesian(worldCenter);
    const centerLLA = [
      Cesium.Math.toDegrees(cartographic.longitude),
      Cesium.Math.toDegrees(cartographic.latitude),
      cartographic.height,
    ];

    // 创建新层
    const newLayer = {
      positions: newPositions,
      indices: new Uint16Array(currentLayer.indices),
      color: color,
      show: true,
      keyIndex: newKeyIndex,
      centerPoint: centerLLA,
    };

    // 添加到数组并更新Map索引
    this.GridCellLayer.push(newLayer);
    const newLayerIndex = this.GridCellLayer.length - 1;
    this.GridCellMap.set(mapKey, newLayerIndex);

    // 更新当前层指针
    this.currentLayerIndex = newLayerIndex;

    // 重新构建几何数据
    this.rebuildGeometry();
    return this;
  }

  // 重新构建几何数据
  rebuildGeometry () {
    let totalVertices = 0;
    let totalIndices = 0;

    this.GridCellLayer.forEach((layer) => {
      totalVertices += layer.positions.length;
      totalIndices += layer.indices.length;
    });

    const newPositions = new Float64Array(totalVertices);
    const newIndices = new Uint16Array(totalIndices);

    let posOffset = 0;
    let idxOffset = 0;
    let vertexCount = 0;

    this.GridCellLayer.forEach((layer) => {
      newPositions.set(layer.positions, posOffset);

      for (let i = 0; i < layer.indices.length; i++) {
        newIndices[idxOffset + i] = layer.indices[i] + vertexCount;
      }

      posOffset += layer.positions.length;
      idxOffset += layer.indices.length;
      vertexCount += layer.positions.length / 3;
    });

    this.positions = newPositions;
    this.indices = newIndices;
  }

  // 销毁所有primitives
  destroy () {
    if (this.primitiveRed && !this.primitiveRed.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveRed);
    }
    if (this.primitiveYellow && !this.primitiveYellow.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveYellow);
    }
    if (this.primitiveGreen && !this.primitiveGreen.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveGreen);
    }
    if (this.primitiveDarkGreen && !this.primitiveDarkGreen.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveDarkGreen);
    }
    if (this.primitiveWhite && !this.primitiveWhite.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveWhite);
    }
    if (this.edgePrimitive && !this.edgePrimitive.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.edgePrimitive);
    }

    this.primitiveRed = null;
    this.primitiveYellow = null;
    this.primitiveGreen = null;
    this.primitiveDarkGreen = null;
    this.primitiveWhite = null;
    this.edgePrimitive = null;
  }

  // 重置GridCell，清空Map和数组
  reset (position) {
    this.destroy();

    // 清空Map和数组
    this.GridCellMap.clear();
    this.GridCellLayer = [];
    this.currentLayerIndex = 0;
    this.currentUAVLayer = null;

    if (position) {
      this.position = position;
      const cartesian = Cesium.Cartesian3.fromDegrees(
        position[0],
        position[1],
        position[2]
      );
      const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
      const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        cartesian,
        hpr
      );
      this.modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
        cartesian,
        orientation,
        new Cesium.Cartesian3(1, 1, 1)
      );

      this.inverseMatrix = Cesium.Matrix4.inverse(
        this.modelMatrix,
        new Cesium.Matrix4()
      );
    }

    this.initGeometryData();
    console.log("GridCell已重置，Map和数组已清空并重新初始化");
    return this;
  }

  /**
   * 根据MQTT传入的经纬度点位计算与中心点的偏移量
   */
  getKeyIndexByLLA (mqttPosition) {
    const targetCartesian = Cesium.Cartesian3.fromDegrees(
      mqttPosition[0],
      mqttPosition[1],
      mqttPosition[2] || 0
    );

    const localPosition = Cesium.Matrix4.multiplyByPoint(
      this.inverseMatrix,
      targetCartesian,
      new Cesium.Cartesian3()
    );

    const gridUnitSize = this.halfSize * 2;
    const leftRightOffset = Math.round(-localPosition.x / gridUnitSize);
    const frontBackOffset = Math.round(-localPosition.y / gridUnitSize);
    const upDownOffset = Math.round(localPosition.z / gridUnitSize);

    return [leftRightOffset, frontBackOffset, upDownOffset];
  }

  /**
   * 改变方格的颜色 - Map优化版本
   */
  changeColor (options = {}) {
    const {
      position,
      color,
      isGridColor = false,
      mode = 0
    } = options;

    if (!Array.isArray(position) || position.length < 2) {
      console.error("位置参数格式不正确，应为[经度,纬度,高度]");
      return this;
    }

    if (!color || !this.allColor[color]) {
      console.error("无效的颜色值，应为'Red', 'Yellow', 'Green', 'DarkGreen'或'White'");
      return this;
    }

    // 坐标转换 - 将经纬度转换为局部坐标系
    const height = position.length > 2 ? position[2] : 0;
    const posCartesian = Cesium.Cartesian3.fromDegrees(
      position[0],
      position[1],
      height
    );

    const localPoint = Cesium.Matrix4.multiplyByPoint(
      this.inverseMatrix,
      posCartesian,
      new Cesium.Cartesian3()
    );

    // 如果是无人机位置更新，先清除之前的无人机位置颜色
    if (isGridColor && this.currentUAVLayer) {
      this.currentUAVLayer.color = color;
      this.currentUAVLayer = null;
    }

    let targetLayer = null;

    // mode=1时，使用原版遍历逻辑来确保正确的批量更新行为
    if (mode === 1) {
      // 使用原版的遍历逻辑
      for (const layer of this.GridCellLayer) {
        if (!layer.keyIndex) continue;

        if (this.isPointInCube(localPoint, layer)) {
          targetLayer = layer;
          break;
        } else {
          // mode=1时，检查每一个元素的颜色是不是传入的color，如果不是则改变
          if (layer.color !== color) {
            layer.color = color;
          }
        }
      }
    } else {
      // mode=0时，使用Map优化进行O(1)查找
      const targetKeyIndex = this.getKeyIndexByLLA(position);
      const mapKey = this.getMapKey(targetKeyIndex);
      const targetLayerIndex = this.GridCellMap.get(mapKey);

      if (targetLayerIndex !== undefined) {
        targetLayer = this.GridCellLayer[targetLayerIndex];
      } else {
        // Map查找失败，回退到遍历查找
        for (const layer of this.GridCellLayer) {
          if (!layer.keyIndex) continue;

          if (this.isPointInCube(localPoint, layer)) {
            targetLayer = layer;
            break;
          }
        }
      }
    }

    // 更新找到的目标立方体颜色
    if (targetLayer) {
      const finalColor = isGridColor ? 'DarkGreen' : color;

      if (targetLayer.color !== finalColor || targetLayer.show === false) {
        if (isGridColor) {
          this.currentUAVLayer = targetLayer;
        }

        targetLayer.color = finalColor;
        targetLayer.show = true;

        this.rebuildGeometry();
        this.drawBox();
      }
    } else {
      console.warn(`查找失败: 未找到坐标 [${position}] 对应的方格`);
    }

    return this;
  }

  drawBox () {
    // 按颜色分组整合数据
    const colorGroups = {
      Red: { positions: [], indices: [], vertexCount: 0 },
      Yellow: { positions: [], indices: [], vertexCount: 0 },
      Green: { positions: [], indices: [], vertexCount: 0 },
      DarkGreen: { positions: [], indices: [], vertexCount: 0 },
      White: { positions: [], indices: [], vertexCount: 0 },
    };

    // 按颜色分配立方体
    this.GridCellLayer.forEach((layer) => {
      if (layer.show === false) return;

      const color = layer.color || "White";
      if (!colorGroups[color]) {
        console.warn(`未知颜色: ${color}, 将使用White`);
        layer.color = "White";
      }

      for (let i = 0; i < layer.positions.length; i++) {
        colorGroups[color].positions.push(layer.positions[i]);
      }

      for (let i = 0; i < layer.indices.length; i++) {
        colorGroups[color].indices.push(
          layer.indices[i] + colorGroups[color].vertexCount
        );
      }

      colorGroups[color].vertexCount += layer.positions.length / 3;
    });

    // 清除现有primitives
    this.destroy();

    // 为每种颜色创建primitive
    if (colorGroups.Red.positions.length > 0) {
      this.primitiveRed = this.createCubePrimitive(
        this.allColor.Red,
        new Uint16Array(colorGroups.Red.indices),
        new Float64Array(colorGroups.Red.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveRed);
    }

    if (colorGroups.Yellow.positions.length > 0) {
      this.primitiveYellow = this.createCubePrimitive(
        this.allColor.Yellow,
        new Uint16Array(colorGroups.Yellow.indices),
        new Float64Array(colorGroups.Yellow.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveYellow);
    }

    if (colorGroups.Green.positions.length > 0) {
      this.primitiveGreen = this.createCubePrimitive(
        this.allColor.Green,
        new Uint16Array(colorGroups.Green.indices),
        new Float64Array(colorGroups.Green.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveGreen);
    }

    if (colorGroups.DarkGreen.positions.length > 0) {
      this.primitiveDarkGreen = this.createCubePrimitive(
        this.allColor.DarkGreen,
        new Uint16Array(colorGroups.DarkGreen.indices),
        new Float64Array(colorGroups.DarkGreen.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveDarkGreen);
    }

    if (colorGroups.White.positions.length > 0) {
      this.primitiveWhite = this.createCubePrimitive(
        this.allColor.White,
        new Uint16Array(colorGroups.White.indices),
        new Float64Array(colorGroups.White.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveWhite);
    }

    // 处理边缘线
    if (this.edgePrimitive && !this.edgePrimitive.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.edgePrimitive);
      this.edgePrimitive = this.createEdgesPrimitive();
      this.viewer.scene.primitives.add(this.edgePrimitive);
    } else {
      this.edgePrimitive = this.createEdgesPrimitive();
      this.viewer.scene.primitives.add(this.edgePrimitive);
    }

    return {
      primitiveRed: this.primitiveRed,
      primitiveYellow: this.primitiveYellow,
      primitiveGreen: this.primitiveGreen,
      primitiveDarkGreen: this.primitiveDarkGreen,
      primitiveWhite: this.primitiveWhite,
      edgePrimitive: this.edgePrimitive,
    };
  }

  // 创建立方体primitive
  createCubePrimitive (color, indicesArr, positionsArr) {
    const instanceColor = color || new Cesium.Color(1.0, 1.0, 1.0, 0.2);
    const oneIndices = indicesArr || this.indices;
    const onePositions = positionsArr || this.positions;

    return new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.Geometry({
          attributes: {
            position: new Cesium.GeometryAttribute({
              componentDatatype: Cesium.ComponentDatatype.DOUBLE,
              componentsPerAttribute: 3,
              values: onePositions,
            }),
          },
          indices: oneIndices,
          primitiveType: Cesium.PrimitiveType.TRIANGLES,
          boundingSphere: Cesium.BoundingSphere.fromVertices(onePositions),
          vertexFormat: Cesium.VertexFormat.ALL,
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(instanceColor),
        },
        modelMatrix: this.modelMatrix,
      }),
      appearance: new Cesium.PerInstanceColorAppearance({
        flat: true,
        translucent: true,
        vertexFormat: Cesium.VertexFormat.ALL,
      }),
      asynchronous: false,
      releaseGeometryInstances: false,
      updatersPerAttribute: 1,
    });
  }

  /**
   * 根据偏移量数组添加立方体 - Map优化版本
   */
  extendByOffsets (offsetsArray, color) {
    if (!Array.isArray(offsetsArray) || offsetsArray.length !== 3) {
      console.error("偏移量数组格式不正确，应为[左右偏移量,前后偏移量,上下偏移量]");
      return this;
    }

    offsetsArray.forEach((offset, index) => {
      if (offset === 0) return;

      let direction = [0, 0, 0];
      direction[index] = offset > 0 ? 1 : -1;
      const directionString = direction.join("_");

      const absOffset = Math.abs(offset);
      for (let i = 0; i < absOffset; i++) {
        this.extend(directionString, 1, color);
      }
    });

    return this;
  }

  /**
   * 加载网格数据json，绘制整个网格 - Map优化版本
   */
  loadGridDataJson (jsonData, color = 'White', fillGaps = true) {
    if (!Array.isArray(jsonData) || jsonData.length === 0) {
      console.warn('网格数据为空或格式不正确');
      return this;
    }

    if (!this.allColor[color]) {
      console.warn(`无效的颜色值: ${color}，将使用默认颜色White`);
      color = 'White';
    }

    if (this.GridCellLayer.length > 0) {
      this.reset(jsonData[0]);
    }

    const optimizedData = jsonData;

    for (let i = 0; i < optimizedData.length; i++) {
      const pointData = optimizedData[i];

      if (!Array.isArray(pointData) || pointData.length < 2) {
        console.warn(`跳过无效的点位数据: ${pointData}`);
        continue;
      }

      const position = [
        pointData[0],
        pointData[1],
        pointData.length > 2 ? pointData[2] : 0
      ];

      if (i === 0) {
        if (this.GridCellLayer.length > 0) {
          this.GridCellLayer[0].color = color;
        }
        continue;
      }

      if (fillGaps) {
        const diffIndexXYZ1 = this.GridCellLayer[this.currentLayerIndex].keyIndex;
        const diffIndexXYZ2 = this.getKeyIndexByLLA(position);

        const offsets = [
          diffIndexXYZ2[0] - diffIndexXYZ1[0],
          diffIndexXYZ2[1] - diffIndexXYZ1[1],
          diffIndexXYZ2[2] - diffIndexXYZ1[2],
        ];

        this.extendByOffsets(offsets, color);
      } else {
        this.createCubeAtPosition(position, color);
      }
    }

    this.rebuildGeometry();
    this.drawBox();

    console.log(`网格数据加载完成，共创建 ${this.GridCellLayer.length} 个立方体，${fillGaps ? '补全模式' : '不补全模式'}`);
    return this;
  }

  /**
   * 绘制单个方格 - Map优化版本
   */
  drawSingleBox (position, color = 'White', fillGaps = true) {
    if (!Array.isArray(position) || position.length < 2) {
      console.error("位置参数格式不正确，应为[经度,纬度,高度]");
      return this;
    }

    if (!this.allColor[color]) {
      console.warn(`无效的颜色值: ${color}，将使用默认颜色White`);
      color = 'White';
    }

    const normalizedPosition = [
      position[0],
      position[1],
      position.length > 2 ? position[2] : 0
    ];

    if (this.GridCellLayer.length === 0) {
      console.warn("没有基础图层，请先初始化GridCell或加载网格数据");
      return this;
    }

    if (fillGaps) {
      const firstLayer = this.GridCellLayer[0];
      if (firstLayer && firstLayer.color === 'White') {
        firstLayer.color = color;
      }

      const currentKeyIndex = this.GridCellLayer[this.currentLayerIndex].keyIndex;
      const targetKeyIndex = this.getKeyIndexByLLA(normalizedPosition);

      const xOffset = targetKeyIndex[0] - currentKeyIndex[0];
      const yOffset = targetKeyIndex[1] - currentKeyIndex[1];
      const zOffset = targetKeyIndex[2] - currentKeyIndex[2];

      this.extendByOffsets([xOffset, yOffset, zOffset], color);
    } else {
      this.createCubeAtPosition(normalizedPosition, color);
    }

    this.rebuildGeometry();
    this.drawBox();

    console.log(`已绘制单个方格，位置: [${normalizedPosition}]，颜色: ${color}，${fillGaps ? '补全模式' : '不补全模式'}`);
    return this;
  }

  /**
   * 判断一个点是否在立方体内部（优化版本）
   */
  isPointInCube (localPoint, layer) {
    const cubeSize = this.halfSize * 2;

    const cubeCenter = new Cesium.Cartesian3(
      -layer.keyIndex[0] * cubeSize,
      -layer.keyIndex[1] * cubeSize,
      layer.keyIndex[2] * cubeSize
    );

    const minX = cubeCenter.x - this.halfSize;
    const maxX = cubeCenter.x + this.halfSize;
    const minY = cubeCenter.y - this.halfSize;
    const maxY = cubeCenter.y + this.halfSize;
    const minZ = cubeCenter.z - this.halfSize;
    const maxZ = cubeCenter.z + this.halfSize;

    const isInside =
      localPoint.x >= minX && localPoint.x <= maxX &&
      localPoint.y >= minY && localPoint.y <= maxY &&
      localPoint.z >= minZ && localPoint.z <= maxZ;

    return isInside;
  }

  /**
   * 在指定位置直接创建立方体（不补全中间的空隙）- Map优化版本
   */
  createCubeAtPosition (position, color = 'White') {
    if (!Array.isArray(position) || position.length < 2) {
      console.error("位置参数格式不正确，应为[经度,纬度,高度]");
      return this;
    }

    if (!this.allColor[color]) {
      console.warn(`无效的颜色值: ${color}，将使用默认颜色White`);
      color = 'White';
    }

    const normalizedPosition = [
      position[0],
      position[1],
      position.length > 2 ? position[2] : 0
    ];

    const targetKeyIndex = this.getKeyIndexByLLA(normalizedPosition);
    const mapKey = this.getMapKey(targetKeyIndex);

    // 使用Map进行O(1)查找
    const existingLayerIndex = this.GridCellMap.get(mapKey);

    if (existingLayerIndex !== undefined) {
      console.log("已存在相同keyIndex的立方体，更新颜色");
      this.GridCellLayer[existingLayerIndex].color = color;
      this.GridCellLayer[existingLayerIndex].show = true;
      return this;
    }

    const baseCubePositions = new Float64Array([
      -this.halfSize, -this.halfSize, -this.halfSize,
      this.halfSize, -this.halfSize, -this.halfSize,
      this.halfSize, this.halfSize, -this.halfSize,
      -this.halfSize, this.halfSize, -this.halfSize,
      -this.halfSize, -this.halfSize, this.halfSize,
      this.halfSize, -this.halfSize, this.halfSize,
      this.halfSize, this.halfSize, this.halfSize,
      -this.halfSize, this.halfSize, this.halfSize,
    ]);

    const gridUnitSize = this.halfSize * 2;
    const newPositions = new Float64Array(baseCubePositions.length);

    const cubeCenter = new Cesium.Cartesian3(
      -targetKeyIndex[0] * gridUnitSize,
      -targetKeyIndex[1] * gridUnitSize,
      targetKeyIndex[2] * gridUnitSize
    );

    for (let i = 0; i < baseCubePositions.length; i += 3) {
      const relativeX = baseCubePositions[i];
      const relativeY = baseCubePositions[i + 1];
      const relativeZ = baseCubePositions[i + 2];

      newPositions[i] = cubeCenter.x + relativeX;
      newPositions[i + 1] = cubeCenter.y + relativeY;
      newPositions[i + 2] = cubeCenter.z + relativeZ;
    }

    const newIndices = new Uint16Array([
      0, 1, 2, 0, 2, 3,
      4, 5, 6, 4, 6, 7,
      0, 1, 5, 0, 5, 4,
      1, 2, 6, 1, 6, 5,
      2, 3, 7, 2, 7, 6,
      3, 0, 4, 3, 4, 7,
    ]);

    const worldCenter = Cesium.Matrix4.multiplyByPoint(
      this.modelMatrix,
      cubeCenter,
      new Cesium.Cartesian3()
    );
    const cartographic = Cesium.Cartographic.fromCartesian(worldCenter);
    const centerLLA = [
      Cesium.Math.toDegrees(cartographic.longitude),
      Cesium.Math.toDegrees(cartographic.latitude),
      cartographic.height,
    ];

    const newLayer = {
      positions: newPositions,
      indices: newIndices,
      color: color,
      show: true,
      keyIndex: targetKeyIndex,
      centerPoint: centerLLA,
    };

    // 添加到数组并更新Map索引
    this.GridCellLayer.push(newLayer);
    const newLayerIndex = this.GridCellLayer.length - 1;
    this.GridCellMap.set(mapKey, newLayerIndex);

    console.log(`在位置 [${normalizedPosition}] 创建立方体，keyIndex: [${targetKeyIndex}]，颜色: ${color}`);
    return this;
  }

  /**
   * 创建立方体边缘线 - Map优化版本
   */
  createEdgesPrimitive () {
    let edgeIndices = [];
    let vertexOffset = 0;

    this.GridCellLayer.forEach((layer) => {
      const vertexCount = layer.positions.length / 3;
      const layerEdgeIndices = [
        // 底面四条边
        vertexOffset + 0, vertexOffset + 1,
        vertexOffset + 1, vertexOffset + 2,
        vertexOffset + 2, vertexOffset + 3,
        vertexOffset + 3, vertexOffset + 0,
        // 顶面四条边
        vertexOffset + 4, vertexOffset + 5,
        vertexOffset + 5, vertexOffset + 6,
        vertexOffset + 6, vertexOffset + 7,
        vertexOffset + 7, vertexOffset + 4,
        // 连接顶面和底面的四条边
        vertexOffset + 0, vertexOffset + 4,
        vertexOffset + 1, vertexOffset + 5,
        vertexOffset + 2, vertexOffset + 6,
        vertexOffset + 3, vertexOffset + 7,
      ];

      edgeIndices = edgeIndices.concat(layerEdgeIndices);
      vertexOffset += vertexCount;
    });

    const edgeColorValues = new Uint8Array((this.positions.length / 3) * 4);

    let currentVertexIndex = 0;
    this.GridCellLayer.forEach((layer) => {
      if (layer.show === false) {
        currentVertexIndex += layer.positions.length / 3;
        return;
      }

      const layerColor = layer.color || 'White';
      let cesiumColor;
      if (this.allColor[layerColor]) {
        cesiumColor = this.allColor[layerColor];
      } else {
        console.warn(`未找到颜色 ${layerColor}，使用默认白色`);
        cesiumColor = this.allColor.White;
      }

      const r = Math.floor(cesiumColor.red * 255);
      const g = Math.floor(cesiumColor.green * 255);
      const b = Math.floor(cesiumColor.blue * 255);
      const a = 255;

      const vertexCount = layer.positions.length / 3;
      for (let i = 0; i < vertexCount; i++) {
        const colorIndex = (currentVertexIndex + i) * 4;
        edgeColorValues[colorIndex] = r;
        edgeColorValues[colorIndex + 1] = g;
        edgeColorValues[colorIndex + 2] = b;
        edgeColorValues[colorIndex + 3] = a;
      }

      currentVertexIndex += vertexCount;
    });

    return new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.Geometry({
          attributes: {
            position: new Cesium.GeometryAttribute({
              componentDatatype: Cesium.ComponentDatatype.DOUBLE,
              componentsPerAttribute: 3,
              values: this.positions,
            }),
            color: new Cesium.GeometryAttribute({
              componentDatatype: Cesium.ComponentDatatype.UNSIGNED_BYTE,
              componentsPerAttribute: 4,
              values: edgeColorValues,
              normalize: true,
            }),
          },
          indices: new Uint16Array(edgeIndices),
          primitiveType: Cesium.PrimitiveType.LINES,
          boundingSphere: Cesium.BoundingSphere.fromVertices(this.positions),
          vertexFormat: Cesium.VertexFormat.POSITION_AND_COLOR,
        }),
        modelMatrix: this.modelMatrix,
      }),
      appearance: new Cesium.PerInstanceColorAppearance({
        flat: true,
        translucent: false,
        vertexFormat: Cesium.VertexFormat.POSITION_AND_COLOR,
        renderState: {
          lineWidth: Math.min(2.0, this.viewer.scene.maximumAliasedLineWidth),
          depthTest: { enabled: true },
          depthMask: true,
        },
      }),
      asynchronous: false,
      releaseGeometryInstances: false,
      allowPicking: false,
    });
  }
}